package com.airsystem.pos.bengkel.controller.report;

import java.awt.Frame;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;

import org.apache.log4j.Logger;

import com.airsystem.pos.bengkel.entity.Tagihan;
import com.airsystem.pos.bengkel.interfaces.IReport;
import com.airsystem.pos.bengkel.model.report.BillingReportModel;
import com.airsystem.pos.bengkel.service.LaporanBulananServices;
import com.airsystem.pos.bengkel.util.Preconditions;

/**
 * @author Budi Oktaviyan <budi.oktaviyan@icloud.com>
 */
public class BillingReportController extends BillingReportModel implements IReport {
	private static final Logger LOG = Logger.getLogger(BillingReportController.class.getSimpleName());

	private LaporanBulananServices laporanBulananServices = new LaporanBulananServices();

	public BillingReportController() {
		super();
	}

	public void print() {
		try {
			Preconditions.checkEmpty(bulanCombo);
			Preconditions.checkEmpty(tahunCombo);
		} catch (IllegalArgumentException e) {
			JOptionPane.showMessageDialog(this, "Silahkan pilih data!", "Pesan", JOptionPane.WARNING_MESSAGE);

			return;
		}

		try {
			List<Tagihan> tagihans = laporanBulananServices.print(getPeriode());

			JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(tagihans);

			Map<String, Object> parameter = new HashMap<String, Object>();
			parameter.put("periode_param", getPeriode().replace("/", " "));

			InputStream inputStream = EmployeeReportController.class.getResourceAsStream("/reports/BillingReport.jasper");

			JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inputStream);

			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameter, beanCollectionDataSource);

			jasperViewer = new JasperViewer(jasperPrint, false);
			jasperViewer.setTitle("Laporan Tagihan Bulanan");
			jasperViewer.setExtendedState(Frame.MAXIMIZED_BOTH);
			jasperViewer.setVisible(true);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(BillingReportController.this, "Load data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}
}